package redisx

import (
	"context"
	"time"

	"github.com/redis/go-redis/v9"
)

var Client redis.UniversalClient

var ctx context.Context

// InitCache 初始化缓存
func InitCache(cfg Config) error {
	Client = redis.NewUniversalClient(&redis.UniversalOptions{
		Addrs:            cfg.Addrs,
		Username:         cfg.Username,
		Password:         cfg.Password,
		SentinelUsername: cfg.SentinelUsername,
		SentinelPassword: cfg.SentinelPassword,
		DB:               cfg.DB,
		MasterName:       cfg.MasterName,
		PoolFIFO:         cfg.PoolFIFO,
		PoolSize:         cfg.PoolSize,
		MinIdleConns:     cfg.MinIdleConns,
		MaxIdleConns:     cfg.MaxIdleConns,
		DialTimeout:      time.Duration(cfg.DialTimeout) * time.Second,
		ReadTimeout:      time.Duration(cfg.ReadTimeout) * time.Second,
		WriteTimeout:     time.Duration(cfg.WriteTimeout) * time.Second,
		PoolTimeout:      time.Duration(cfg.PoolTimeout) * time.Second,
		MaxRetries:       cfg.MaxRetries,
		MinRetryBackoff:  time.Duration(cfg.MinRetryBackoff) * time.Millisecond,
		MaxRetryBackoff:  time.Duration(cfg.MaxRetryBackoff) * time.Millisecond,
	})

	ctx = context.Background()
	return Client.Ping(ctx).Err()
}
